package Model.Game;

import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.util.ArrayList;

import javax.swing.Timer;

import Model.Beat.BeatModelInterface;
import View.BPMObserver;
import View.BeatObserver;

public class GameModel implements BeatModelInterface,Runnable{
	
	ArrayList<Object> beatObservers = new ArrayList<Object>();
	ArrayList<Object> bpmObservers = new ArrayList<Object>();
	
    private int clicks;
    private boolean b;
    private boolean timeLimit;
    private boolean dontBeat;
    private int currentTime;
    
    private Thread thread;
    Timer timer;
    Timer timer2;
    
    public GameModel(){
		this.b=false;
		this.timeLimit=false;
		this.dontBeat = true;
		this.currentTime = 10;
		thread = new Thread(this);
		thread.start();
		
		timer = new Timer(10000, new ActionListener(){
			@Override
			public void actionPerformed(ActionEvent e) {
				timeLimit = true;		
			}
		});
		
		timer2 = new Timer(1000, new ActionListener(){
			@Override
			public void actionPerformed(ActionEvent e) {
				if(currentTime != 0){
					currentTime--;
					notifyBPMObservers();
				} else{
					timer2.stop();
				}
			}	
		});
		
    }
    	
    

	@Override
	public void run() {
		try{
		while(true){
			//this.clicks++;
			if(b){
				if(!timeLimit){
					if(dontBeat){
						notifyBeatObservers();
					}
					notifyBPMObservers();
				}
				b=false;
			}
			Thread.sleep(10);
		}}catch(InterruptedException ex){
			;;
		}
		
	}
	
	public void reset(){
		this.currentTime = 10;
		notifyBPMObservers();
		this.clicks=0;
		this.timeLimit = false;
		dontBeat = false;
		timer.stop();
		timer2.stop();
		this.b=true;
	}


	private void notifyBPMObservers() {
		// TODO Auto-generated method stub
		for(int i= 0; i< bpmObservers.size();i++){
			((BPMObserver)bpmObservers.get(i)).updateBPM();
		}
	}



	public void notifyBeatObservers() {
		for(int i = 0; i < beatObservers.size(); i++) {
			BeatObserver observer = (BeatObserver)beatObservers.get(i);
			observer.updateBeat();
		}
	}


	@Override
	public void initialize() {
		// TODO Auto-generated method stub
		
	}

	@Override
	public void on() {
		this.clicks=0;
		
	}

	@Override
	public void off() {
		this.clicks=0;
		
	}

	@Override
	public void setBPM(int bpm) {
		this.clicks=bpm;
		
	}
	
	public void increaseBPM(){
		if(clicks == 0){
			timer2.start();
			timer.start();
		}
		dontBeat = true;
		this.clicks++;
		this.b=true;
	}

	@Override
	public int getBPM() {
		return this.clicks;
	}
	
	public int getCurrentTime(){
		return this.currentTime;
	}

	public void registerObserver(BeatObserver o) {
		beatObservers.add(o);
	}

	public void removeObserver(BeatObserver o) {
		int i = beatObservers.indexOf(o);
		if (i >= 0) {
			beatObservers.remove(i);
		}
	}


	public void registerObserver(BPMObserver o) {
		bpmObservers.add(o);
	}

	public void removeObserver(BPMObserver o) {
		int i = bpmObservers.indexOf(o);
		if (i >= 0) {
			bpmObservers.remove(i);
		}
	}
	
}
